package com.meepo.framework.design.tabs.sample

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.meepo.framework.design.tabs.FragmentContainerAdapter
import com.meepo.framework.design.tabs.MagicIndicator

class FragmentContainerManager(
    private val fragmentManager: FragmentManager,
    val fragments: List<Fragment>,
    private val fragmentContainerId: Int,
    magicIndicator: MagicIndicator
) {

    private val mFragmentContainerAdapter: FragmentContainerAdapter = FragmentContainerAdapter(magicIndicator)

    fun switchPages(index: Int) {

        mFragmentContainerAdapter.handlePageSelected(index, true)

        val fragmentTransaction = fragmentManager.beginTransaction()
        var fragment: Fragment
        var i = 0
        val j: Int = fragments.size
        while (i < j) {
            if (i == index) {
                i++
                continue
            }
            fragment = fragments[i]
            if (fragment.isAdded) {
                fragmentTransaction.hide(fragment)
            }
            i++
        }
        fragment = fragments[index]
        if (fragment.isAdded) {
            fragmentTransaction.show(fragment)
        } else {
            fragmentTransaction.add(fragmentContainerId, fragment)
        }
        fragmentTransaction.commitAllowingStateLoss()
    }

}